package com.yitianyigexiangfa.netty.design.pattern.reactor.demo;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.Set;

public class Reactor implements Runnable {

    Selector selector;

    public Reactor() throws IOException {
        selector = Selector.open();
    }

    public void run() {
        try {
            while (!Thread.interrupted()) {
                selector.select();
                Set<SelectionKey> selected = selector.selectedKeys();
                Iterator it =  selected.iterator();
                while (it.hasNext()){
                    dispatch((SelectionKey)(it.next()));
                    selected.clear();
                }
            }
        } catch (IOException e) {

        }
    }

    void dispatch(SelectionKey k) {
        Runnable r = (Runnable) k.attachment();
        if (r != null) {
            r.run();
        }
    }
}
